package com.example.server.controller;

import com.example.server.common.Result;
import com.example.server.entity.Conversation;
import com.example.server.entity.Message;
import com.example.server.service.ConversationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/conversation")
public class ConversationController {

    @Autowired
    private ConversationService conversationService;

    //创建对话
    @PostMapping("/create")
    public Result createConversation(@RequestParam Integer user_id,@RequestParam Integer script_id) {
        Integer id =conversationService.createConversation(user_id,script_id);
        return Result.success(id);
    }

    // 删除对话（存档）
    @DeleteMapping("/delete/{id}")
    public Result deleteConversationById(@PathVariable Integer id) {
        try {
            conversationService.deleteConversation(id);
            return Result.success();
        } catch (Exception e) {
            return Result.error("Failed to delete conversation");
        }
    }
    //获取用户的历史对话
    @GetMapping("/list/{user_id}")
    public Result getUserConversations(@PathVariable Integer user_id) {
        List<Conversation> conversations = conversationService.getUserConversations(user_id);
        return Result.success(conversations);
    }

    //获取某个对话的对话信息
    @GetMapping("/messages/{conversation_id}")
    public Result getMessages(@PathVariable Integer conversation_id,
                              @RequestParam Integer user_id) {
        Conversation conversation = conversationService.getConversation(conversation_id);
        if (conversation != null && conversation.getUser_id().equals(user_id)) {
            List<Message> messages = conversationService.getMessages(conversation_id);
            return Result.success(messages);
        } else {
            return Result.error("forbidden quest");
        }
    }

    //保存用户的某个对话的某条信息
    @PostMapping("/message")
    public Result saveMessage(@RequestParam Integer user_id,
                              @RequestParam Integer conversation_id,
                              @RequestParam String sender,
                              @RequestParam String content) {
        Conversation conversation = conversationService.getConversation(conversation_id);
        if (conversation != null && conversation.getUser_id().equals(user_id)) {
            conversationService.saveMessage(conversation_id, sender, content);
            return Result.success();
        } else {
            return Result.error("error quest");
        }
    }
}


